package org.syndicate.domain;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.TypedQuery;

import org.springframework.roo.addon.entity.RooEntity;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.transaction.annotation.Transactional;

/**
 * Transaction of loan principal payment.
 * 
 * @author akiraabe
 */
@RooJavaBean
@RooToString
@RooEntity(inheritanceType = "JOINED")
public class PrincipalPayment extends AbstractTransaction {
	
	private String loanName;
	
	/**
	 * {@inheritDoc}
	 * <br/>Borrower pays principal.
	 */
	@Transactional
	@Override
	public AbstractPosition execute() {
		
		System.out.println("Principal#execute");

		this.setDiscriminator("PrincipalPayment");
		
		// Find existing Loan.
		Loan loan = Loan.findLoansByName(this.loanName).getSingleResult();
		PaymentDetail paymentDetail = null;
		for (PaymentDetail pd : loan.getPaymentDetails()) {
			if (this.getTransactionDate().equals(pd.getPaymentDate())) {
				paymentDetail = pd;
			}
		}
		System.out.println(paymentDetail);
		this.setAmount(new Double(paymentDetail.getPrincipal()));
		
		// execute transaction!
		loan.apply(this);
		
		return loan;
	}

}
